package org.hz.util;


import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.beanutils.BeanUtils;
import org.lsx.commons.crypto.CryptoException;

import com.mymyti.util.MD5;

public class MacUtil
{

	/**
	 * 校验REQ的MAC
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean checkMac(Object obj, String fieldstr, String mac)
	{
		if ((obj==null)||(fieldstr==null)||(mac==null))
		{
			return false;
		}
		
		StringBuilder sb = new StringBuilder();
		String[] fields = fieldstr.split(",");
		for (int i = 0; i < fields.length; i++)
		{
			try
			{
				String reqValue = BeanUtils.getProperty(obj, fields[i]);
				if (reqValue != null)
				{
					sb.append(reqValue);
				}
			}
			catch (IllegalAccessException e)
			{
				e.printStackTrace();
			}
			catch (InvocationTargetException e)
			{
				e.printStackTrace();
			}
			catch (NoSuchMethodException e)
			{
				e.printStackTrace();
			}
		}

		try
		{

			return checkMacMD5(sb.toString(), mac);
		}
		catch (CryptoException e)
		{
			e.printStackTrace();
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		return false;
	}

	public static String calcMac(Object obj, String fieldstr)
	{
		if ((obj==null)||(fieldstr==null))
		{
			return null;
		}
		
		StringBuilder sb = new StringBuilder();
		String[] fields = fieldstr.split(",");
		for (int i = 0; i < fields.length; i++)
		{
			try
			{
				String respValue = BeanUtils.getProperty(obj, fields[i]);
				if (respValue != null)
				{
					sb.append(respValue);
				}
			}
			catch (IllegalAccessException e)
			{
				e.printStackTrace();
			}
			catch (InvocationTargetException e)
			{
				e.printStackTrace();
			}
			catch (NoSuchMethodException e)
			{
				e.printStackTrace();
			}
		}
		try
		{
			return EncoderByMd5(sb.toString());
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 验证加密文件
	 * 
	 * @param resBodyBA
	 * @param resMacBA
	 * @return
	 * @throws CryptoException
	 * @throws NoSuchAlgorithmException
	 */
	public static boolean checkMacMD5(String resBodyBA, String resMacBA)
			throws CryptoException, NoSuchAlgorithmException
	{

		MD5 md5 = new MD5();
		return md5.verifSign(resBodyBA, resMacBA);

	}

	/**
	 * MD5 加密
	 * 
	 * @param reqData
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String EncoderByMd5(String reqData)
			throws NoSuchAlgorithmException
	{
		MD5 md5 = new MD5();
		return md5.genSign(reqData);
	}

}
